<template>
  <el-cascader
    size="small"
    :props="cityProps"
    placeholder="请选择所在地区"
    v-model="cityValue"
    ref="cascader"
    @change='chooseCity'>
  </el-cascader>
</template>

<script lang="ts">
import { defineComponent, reactive, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
/**
 * 城市选择组件封装
 * @Author yuanyexu
 * @Date 2021-08-03
 */
export default defineComponent({
  name: 'CityChoose',
  props: ['status', 'defaultCitys', 'checkStrictly'],
  emits: ['selected', 'inputValue'],
  setup(props, ctx) {
    const instance = getCurrentInstance();
    const store = useStore();
    let cityValue = reactive([]);
    if (props.status === 'update') {
      cityValue = props.defaultCitys;
    }
    const cityProps = reactive({
      lazy: true,
      checkStrictly: props.checkStrictly || false,
      lazyLoad: async (node:any, resolve:any) => {
        const { level, data } = node;
        const getCity = await store.dispatch('citys/getCity', data.value)
        const citys = getCity.map(item => ({
          value: item.id,
          label: item.name,
          leaf: level >= 2
        }));
        resolve(citys);
      }
    });
    const chooseCity = (data) => {
      const cascader:any = instance.refs.cascader;
      cascader.togglePopperVisible(false)
      const inputValue = cascader.inputValue;
      ctx.emit('selected', data);
      ctx.emit('inputValue', inputValue);
    };
    return {
      cityProps,
      cityValue,
      chooseCity
    };
  },
});
</script>